package service;

import java.net.InetAddress;
import java.net.Socket;
import java.net.URLConnection;
import java.net.URL;
import java.util.Random;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;


public class PageRankService {

    static private int dataCenterIdx = 0;

    /**
     * List of available google datacenter IPs and addresses
     */
    static final public String [] GOOGLE_PR_DATACENTER_IPS = new String[]{
                
                "toolbarqueries.google.com",
                "toolbarqueries.google.com.vn"
                };

    /**
     * Default constructor
     */
    public PageRankService() {

    }

    /**
     * Must receive a domain in form of: "http://www.domain.com"
     * @param domain - (String)
     * @return PR rating (int) or -1 if unavailable or internal error happened.
     */
    public String getPR(String domain) {

        String result = "0";
        JenkinsHash jHash = new JenkinsHash();

        String googlePrResult = "";

        long hash = jHash.hash(("info:" + domain).getBytes());

        String url = "http://"+GOOGLE_PR_DATACENTER_IPS[dataCenterIdx]+"/tbr?client=navclient-auto&hl=en&"+
                "ch=6"+hash+"&ie=UTF-8&oe=UTF-8&features=Rank&q=info:" + domain;

        try {
        	       	
			URLConnection con = new URL(url).openConnection();
			InputStream is = con.getInputStream();
			byte[] buff = new byte[1024];
			int read = is.read(buff);
			while (read > 0) {
				googlePrResult = new String(buff, 0, read);
				read = is.read(buff);
			}

            String[] prResult = googlePrResult.split(":");

            result = prResult[prResult.length-1];
        } catch (Exception e) {
            e.printStackTrace();
        }

        dataCenterIdx++;
        if (dataCenterIdx == GOOGLE_PR_DATACENTER_IPS.length) {
            dataCenterIdx = 0;
        }

        return result;

    }

    public static void main(String [] args) {
        long start = System.currentTimeMillis();
        PageRankService prService = new PageRankService();
        String domain = "http://www.gmail.com";
        if (args.length > 0) {
            domain = args[0];
        }
        System.out.println("Checking " + domain);
        System.out.println("Google PageRank: " + prService.getPR(domain));
        System.out.println("Took: " + (System.currentTimeMillis() - start) + "ms");
    }
}
